/**
 * 页面提供给 iframe 的方法
 */
import { setRefreshToken, setAccessToken } from 'abc-request';

import { portalRequest } from '@/utils/request';
import { zgio } from '@/utils/constJson';
import { ENV_CONFIG } from '@config/env';
import { PR } from '@config/constants/browserEnv';
let { pageCommon } = zgio;

//退出登录
export function logout(rs) {
  // 主服务 退出登录方法
  window.logout?.();
  console.log('iframe 调用了 logout');
}

//刷新token
export function refreshToken(rs) {
  const { data } = rs;
  console.log('iframe 调用了 refreshToken');
  console.log(data);
  setAccessToken(data.accessToken, data.expireIn);
  setRefreshToken(data.refreshToken, data.refreshExpireIn);
}

//埋点
export function statistics(rs) {
  const { data } = rs;
  pageCommon(data.title, {
    ...data.params,
  });
}

//调用主站 request方法
export async function sendRequest(rs, This) {
  const { data } = rs;
  var id = data.id;
  var path = PR;

  try {
    var res = await portalRequest.request(
      data.url,
      {
        ...data.params,
        prefix: ENV_CONFIG['request_uri'] + path,
      },
      {
        noSCOPE: true,
      },
    );

    //写到这里
    var obj = {
      type: 'sendRequestRs',
      data: {
        id: id,
        res: res,
      },
    };
    This.sendMsgToIframe(obj);
    console.log(res, 9999);
  } catch (error) {}
}

export default key => {
  var emptyFN = () => {};
  var maps = {
    logout: logout,
    refreshToken: refreshToken,
    statistics: statistics,
    sendRequest: sendRequest,
  };
  return maps[key] || emptyFN;
};
